package lsy.redis001.lsyredis001.utils;

import lsy.redis001.lsyredis001.entity.Article;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description bean和map互相转换的工具类
 * @Author lsy
 * @Date 上午 11:41 2020/3/17 0017
 * @Param
 * @return
 **/
public class BeanMapUtils {
    public static <T> T mapToBean(Map<String,Object> map, Class<T> clazz)
            throws IllegalAccessException, InstantiationException {
        T t = clazz.newInstance();
        for (Map.Entry<String, Object> current:map.entrySet()){
            Field temField = null;
            try {
                temField = clazz.getDeclaredField(current.getKey());
            } catch (NoSuchFieldException e) {
                continue;
            }
            temField.setAccessible(Boolean.TRUE);
            temField.set(t,current.getValue());
        }
        return t;
    }

    public static Object mapToBean(Map<String,Object> map,Object o){
        try {
            BeanUtils.populate(o,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return o;
    }

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("title","sdfsdf");
        map.put("id",12L);
        map.put("time","123");
        map.put("aa","123");
//        Article article = mapToBean(map, Article.class);
        Article article = (Article)mapToBean(map, new Article());
        System.out.println(article.toString());
    }
}
